package com.edocbase.desktopserver;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import com.edocbase.desktopserver.impl.AnnotationActionMapper;
import com.edocbase.desktopserver.impl.IActionHandler;
import com.edocbase.desktopserver.impl.jetty.JettyDesktopServer;

public class DesktopServerActivator implements BundleActivator {

	private static BundleContext context;
	private ServiceRegistration serverReg;
	private ActionMapper actionMapper = null;
	private static DesktopServerActivator activator = null;
	private ServiceRegistration actionReg;
	
	public DesktopServerActivator() {
		super();
		activator = this;
		actionMapper = new AnnotationActionMapper();
	}

	static BundleContext getContext() {
		return context;
	}

	public static DesktopServerActivator getActivator() {
		return activator;
	}

	public ActionMapper getActionMapper() {
		return actionMapper;
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext bundleContext) throws Exception {
		DesktopServerActivator.context = bundleContext;
		serverReg = context.registerService(IDesktopServer.class.getName(), new JettyDesktopServer(), null);
		actionReg = context.registerService(ActionMapper.class.getName(), actionMapper, null);
		System.out.println("desktop server start.....");
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext bundleContext) throws Exception {
		context.ungetService(serverReg.getReference());
		actionReg.unregister();
		DesktopServerActivator.context = null;
		System.out.println("desktop server stop ......");
	}
	public void scanActions(){
		ServiceReference[] refs;
		try {
			refs = context.getServiceReferences(IActionHandler.class.getName(), null);
			if (refs == null){
				System.out.println("refs is null ........................... ");
			}
			System.out.println(".................");
			for (ServiceReference ref:refs){
				System.out.println(ref);
			}
			System.out.println("end ...........................");

		} catch (InvalidSyntaxException e) {
			e.printStackTrace();
		}
		
	}
}
